package com.xbts.system.service.impl;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.vpc.v2.VpcClient;
import com.huaweicloud.sdk.vpc.v2.model.*;
import com.huaweicloud.sdk.vpc.v2.region.VpcRegion;
import com.xbts.common.config.XbtsConfig;
import com.xbts.common.enums.SettingEnum;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.dto.AccountSetting;
import com.xbts.system.domain.dto.RegionIdDTO;
import com.xbts.system.service.ICloudSecurityService;
import com.xbts.system.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author llk
 * @Date 2023/8/11 15:15
 */
@Service
@Slf4j
public class ICloudSecurityServiceImpl implements ICloudSecurityService {

    @Autowired
    private SettingService settingService;

    @Override
    public NeutronListSecurityGroupsResponse neutronListSecurityGroups(RegionIdDTO<NeutronListSecurityGroupsRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronListSecurityGroupsResponse response = null;
        try {
            response = client.neutronListSecurityGroups(regionIdDTO.getBody());
        } catch (ConnectionException | RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("查询安全组列表失败，错误码：" + e.getErrorCode() + "，错误信息：" + e.getErrorMsg());
        }
        return response;
    }

    @Override
    public NeutronShowSecurityGroupResponse neutronShowSecurityGroup(RegionIdDTO<NeutronShowSecurityGroupRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronShowSecurityGroupResponse response = null;
        try {
            response = client.neutronShowSecurityGroup(regionIdDTO.getBody());
        } catch (ConnectionException | RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("查询安全组失败，错误码：" + e.getErrorCode() + "，错误信息：" + e.getErrorMsg());
        }
        return response;
    }

    @Override
    public NeutronCreateSecurityGroupResponse neutronCreateSecurityGroup(RegionIdDTO<NeutronCreateSecurityGroupRequest> regionIdDTO) {
        NeutronCreateSecurityGroupOption securityGroup = regionIdDTO.getBody().getBody().getSecurityGroup();
        // 取值范围:0-255个字符
        if (securityGroup.getDescription().length( ) > 255) {
            throw new ServiceException("安全组描述信息长度不能超过255个字符");
        }
        // 取值范围:0-255个字符 约束:不允许为“default”
        if (securityGroup.getName().length() > 255 || "default".equals(securityGroup.getName())) {
            throw new ServiceException("安全组名称长度不能超过255个字符且不能为default");
        }
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronCreateSecurityGroupResponse response = null;
        try {
            response = client.neutronCreateSecurityGroup(regionIdDTO.getBody());
        } catch (ConnectionException | RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("创建安全组失败，错误码：" + e.getErrorCode() + "，错误信息：" + e.getErrorMsg());
        }
        return response;
    }

    @Override
    public NeutronUpdateSecurityGroupResponse neutronUpdateSecurityGroup(RegionIdDTO<NeutronUpdateSecurityGroupRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronUpdateSecurityGroupResponse response = null;
        try {
            response = client.neutronUpdateSecurityGroup(regionIdDTO.getBody());
        } catch (Exception e) {
            log.error("更新安全组，错误信息：" + e.getMessage());
        }
        return response;
    }

    @Override
    public NeutronDeleteSecurityGroupResponse neutronDeleteSecurityGroup(RegionIdDTO<NeutronDeleteSecurityGroupRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronDeleteSecurityGroupResponse response = null;
        try {
            response = client.neutronDeleteSecurityGroup(regionIdDTO.getBody());
        } catch (Exception e) {
           log.error("删除安全组失败，错误信息：" + e.getMessage());
        }
        return response;
    }

    @Override
    public NeutronListSecurityGroupRulesResponse neutronListSecurityGroupRules(RegionIdDTO<NeutronListSecurityGroupRulesRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronListSecurityGroupRulesResponse response = null;
        try {
            response = client.neutronListSecurityGroupRules(regionIdDTO.getBody());
        } catch (Exception e) {
            log.error("查询安全组规则列表，错误信息：" + e.getMessage());
        }
        return response;
    }

    @Override
    public NeutronShowSecurityGroupRuleResponse neutronShowSecurityGroupRule(RegionIdDTO<NeutronShowSecurityGroupRuleRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronShowSecurityGroupRuleResponse response = null;
        try {
            response = client.neutronShowSecurityGroupRule(regionIdDTO.getBody());
        } catch (Exception e) {
            log.error("查询安全组规则，错误信息：" + e.getMessage());
        }
        return response;
    }

    @Override
    public NeutronCreateSecurityGroupRuleResponse neutronCreateSecurityGroupRule(RegionIdDTO<NeutronCreateSecurityGroupRuleRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronCreateSecurityGroupRuleResponse response = null;
        try {
            response = client.neutronCreateSecurityGroupRule(regionIdDTO.getBody());
        } catch (Exception e) {
            log.error("创建安全组规则，错误信息：" + e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        return response;
    }

    @Override
    public NeutronDeleteSecurityGroupRuleResponse neutronDeleteSecurityGroupRule(RegionIdDTO<NeutronDeleteSecurityGroupRuleRequest> regionIdDTO) {
        VpcClient client = getVpcClient(regionIdDTO.getRegionId());
        NeutronDeleteSecurityGroupRuleResponse response = null;
        try {
            response = client.neutronDeleteSecurityGroupRule(regionIdDTO.getBody());
        } catch (Exception e) {
            log.error("删除安全组规则，错误信息：" + e.getMessage());
        }
        return response;
    }

    /**
     * 获取VpcClient
     * @param regionId 区域id
     * @return VpcClient
     */
    public VpcClient getVpcClient(String regionId){
        AccountSetting accountSetting = settingService.getAccountSetting(SettingEnum.HUAWEI);

        regionId = StringUtils.isEmpty(regionId) ? accountSetting.getRegionId() : regionId;
        ICredential auth = new BasicCredentials()
                .withAk(accountSetting.getAccessKeyId())
                .withSk(accountSetting.getSecretAccessKey());

        return VpcClient.newBuilder()
                .withCredential(auth)
                .withRegion(VpcRegion.valueOf(regionId))
                .build();
    }
}
